package com.lzq.rabbitmqdemo.advanced_features.listener;

import com.lzq.rabbitmqdemo.advanced_features.constant.Constants;
import com.rabbitmq.client.Channel;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

import java.io.UnsupportedEncodingException;

@Component
public class AckQueueListener {

    /**
     * node/auto测试
     * @param message
     * @param channel
     * @throws Exception
     */
//    @RabbitListener(queues = Constants.ACK_QUEUE)
//    public void ListenerQueue(Message message, Channel channel) throws Exception {
//        System.out.printf("接收到消息:%s, deliveryTag: %d%n",
//                new String(message.getBody(),"UTF-8"),
//                message.getMessageProperties().getDeliveryTag());
//        int num = 3/0;
//        System.out.println("处理完成");
//    }

    /**
     * manual测试
     * @param message
     * @param channel
     * @throws Exception
     */
    @RabbitListener(queues = Constants.ACK_QUEUE)
    public void ListenerQueue(Message message, Channel channel) throws Exception {
        long deliveryTag = message.getMessageProperties().getDeliveryTag();

        try {
            Thread.sleep(1_000);
            System.out.printf("接收到消息:%s, deliveryTag: %d%n",
                    new String(message.getBody(),"UTF-8"),
                    message.getMessageProperties().getDeliveryTag());
            int num = 3/0;
            System.out.println("处理完成");
            channel.basicAck(deliveryTag, true);
        } catch (UnsupportedEncodingException e) {
            channel.basicNack(deliveryTag, true,false);
        }
    }
}
